package com.sskj.mine;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.support.design.widget.BottomSheetDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckedTextView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.allen.library.SuperTextView;
import com.bumptech.glide.Glide;
import com.hey.lib.HeySpinner;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.scwang.smartrefresh.layout.util.DensityUtil;
import com.sskj.common.adapter.slimadapter.IViewInjector;
import com.sskj.common.adapter.slimadapter.SlimAdapter;
import com.sskj.common.adapter.slimadapter.SlimInjector;
import com.sskj.common.base.App;
import com.sskj.common.base.HttpData;
import com.sskj.common.box.decoration.DividerLineItemDecoration;
import com.sskj.common.util.CheckUtil;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.ImageUtil;
import com.sskj.common.util.SPUtil;
import com.sskj.common.util.ToastUtil;
import com.sskj.lib.Constans;
import com.sskj.lib.RConfig;
import com.sskj.lib.RxBusCode;
import com.sskj.lib.SPConfig;
import com.sskj.lib.base.BaseActivity;
import com.sskj.lib.bean.UserData;
import com.sskj.lib.model.room.UserViewModel;
import com.sskj.lib.util.AppCircleCheckUtil;
import com.sskj.lib.util.AppInnerCheckUtil;
import com.sskj.lib.util.AppOuterCheckUtil;
import com.sskj.lib.util.HideUtil;
import com.sskj.mine.bean.InvireTeamRecord;
import com.sskj.mine.bean.PayWayBean;
import com.sskj.mine.bean.PayWayItem;
import com.sskj.mine.component.DaggerUserDataComponent;
import com.sskj.mine.dialog.TipDialog;
import com.sskj.mine.util.MineTipUtil;
import com.wei.android.lib.fingerprintidentify.FingerprintIdentify;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import butterknife.BindView;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subscribers.DisposableSubscriber;
import me.jessyan.autosize.utils.ScreenUtils;

/**
 * @author Hey
 * Create at  2019/05/01
 */
@Route(path = RConfig.MINE_SECURITY_CENTER)
public class SecurityActivity extends BaseActivity<SecurityPresenter> {

    @BindView(R2.id.menu_verify)
    SuperTextView menuVerify;
    @BindView(R2.id.menu_bind_mobile)
    SuperTextView menuBindMobile;
    @BindView(R2.id.menu_bind_email)
    SuperTextView menuBindEmail;
    @BindView(R2.id.menu_chrome)
    SuperTextView menuChrome;
    @BindView(R2.id.menu_login_password)
    SuperTextView menuLoginPassword;
    @BindView(R2.id.menu_pay_password)
    SuperTextView menuPayPassword;
    @BindView(R2.id.security_img)
    ImageView securityImg;
    @BindView(R2.id.menu_seller)
    SuperTextView menuSeller;
    @BindView(R2.id.checkedTextView)
    CheckedTextView checkedTextView;
    private UserData mUserInfo;
    @Inject
    UserViewModel userViewModel;
    @BindView(R2.id.security_bottom_recyclerview)
    RecyclerView mSecurityRecyclerView;
    private SlimAdapter adapter;
    @BindView(R2.id.item_text)
    TextView itemText;
    BottomSheetDialog googleDialog;
    private int googleType;
    private TextView mTvCount;
    private DisposableSubscriber<Long> disposableSubscriber;
    private MaterialDialog materialDialog;
    // 支付方式
    /**
     * 支付方式添加 或 编辑  add/edit
     */
    private String mType = "add";
    private AlertDialog mAlertDialog;
    private View mDialogClose;
    private EditText mDialogInputPayPwd;
    private EditText mDialogInputBankBranch;
    private String mSelectName;
    private EditText mDialogInputBankName;
    private EditText mDialogInputBankCardNum;
    private View mDialogThirdpartyLayout;
    private TextView mDialogThirdpartyName;
    private EditText mDialogInputThirdpartyAccount;
    private EditText dialogInputPaypalName;
    private ImageView mDialogThirdpartyPic;
    private HeySpinner mDialogPayWaySpinner;
    private TextView mDialogRealname;
    private View mDialogCancel;
    private TextView mDialogSubmit;
    private View mDialogBanknumLayout;
    private View dialogPaypalLayout;
    private TextView mDialogThirdpartyPicHint;
    /**
     * 支付方式 微信，支付宝 收款二维码 图片URL
     */
    private String mImagePath;

    private String imgUrl;
    private boolean b = true;
    private EditText et_bankname;
    private TextView tv_name;
    private EditText et_bank_code;
    private EditText et_bank_othername;
    private EditText et_pwd;
    private TextView tv_cancle;
    private TextView tv_confirm;
    private TextView tv_close;
    private Boolean isFingerOn;


    @Override
    public int getLayoutId() {
        return R.layout.mine_activity_security;
    }

    @Override
    public SecurityPresenter getPresenter() {
        return new SecurityPresenter();
    }

    @Override
    public void initView() {
        setTitle(App.INSTANCE.getString(R.string.mine_securityActivity1_j));
        DaggerUserDataComponent.create().inject(this);
        userViewModel.getUsers().observe(this, users -> {
            if (users != null && users.size() > 0) {
                mUserInfo = users.get(0);
            } else {
                mUserInfo = null;
            }
        });
    }

    @Override
    public void initData() {
        //实名认证
        ClickUtil.click(menuVerify, () -> {
            ARouter.getInstance().build(RConfig.MINE_SECURITY_VERIFYHOME).navigation();
        });
        //绑定手机号
        ClickUtil.click(menuBindMobile, () -> {
            if (!AppInnerCheckUtil.checkTradePwd(this, mUserInfo)) {
                return;
            }
            if (TextUtils.isEmpty(mUserInfo.getMobile())) {
                BindMobileActivity.start(this, true);
            } else {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.mine_securityActivity2_j));
            }
        });
        // 绑定邮箱
        ClickUtil.click(menuBindEmail, () -> {
            if (!AppInnerCheckUtil.checkTradePwd(this, mUserInfo)) {
                return;
            }
            if (TextUtils.isEmpty(mUserInfo.getEmail())) {
                BindMobileActivity.start(this, false);
            } else {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.mine_securityActivity3_j));
            }
        });
        //登录密码
        ClickUtil.click(menuLoginPassword, () -> {
            ARouter.getInstance().build(RConfig.MINE_SET_PAY_PWD)
                    .withString("mobile", mUserInfo.getMobile())
                    .withInt("type", 0).navigation();
        });
        //资金密码
        ClickUtil.click(menuPayPassword, () -> {
            ARouter.getInstance().build(RConfig.MINE_SET_PAY_PWD)
                    .withString("mobile", mUserInfo.getMobile())
                    .withInt("type", TextUtils.isEmpty(mUserInfo.getTpwd()) ? 1 : 2).navigation();
        });

        //商家认证
        ClickUtil.click(menuSeller, () -> {  //  0否 1是 2申请商家审核中 3撤销商家审核中
            if (!AppOuterCheckUtil.checkHighAuth(this, mUserInfo)) {  // 高级认证
                return;
            }
            if (mUserInfo.getIs_shop().equals("0") || mUserInfo.getIs_shop().equals("3")) {  // 不是商家 0 未认证  1 待审核  2 已认证
                SellerApplyActivity.start(this);
//                materialDialog = MineTipUtil.showShop(this, mUserInfo.getUsdt(), new MineTipUtil.OnInputList() {
//                    @Override
//                    public void onSure() {
//                        mPresenter.shopVerify();
//                    }
//                });
//                materialDialog.show();
                return;
            }

            if (mUserInfo.getIs_shop().equals("2")) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.mine_securityActivity4_j));
                return;
            }


            new TipDialog(this)
                    .setContent(App.INSTANCE.getString(R.string.mine_securityActivity5_j))
                    .setCancelButtonText(App.INSTANCE.getString(R.string.mine_securityActivity6_j))
                    .setTitle(App.INSTANCE.getString(R.string.mine_securityActivity7_j))
                    .setConfirmButtonText(App.INSTANCE.getString(R.string.mine_securityActivity8_j))
                    .setListener(dialog -> {
                        dialog.dismiss();
                        mPresenter.cancelShop();
                    })
                    .show();
        });

        // 谷歌认证
        ClickUtil.click(menuChrome, () -> {
            if (mUserInfo != null) {
                if (!AppCircleCheckUtil.checkAuth(this, mUserInfo)) {
                    return;
                }
                if (mUserInfo.getIs_start_google() == 0) {
                    startActivity(new Intent(this, VerifyGoogleActivity.class));
                } else {
                    startActivity(new Intent(this, VerifyGoogleActivity.class));
//                    showGoogleDialog();
                }
            }
        });

        isFingerOn = SPUtil.get(SPConfig.IS_FINGER_ON, false);
        checkedTextView.setChecked(isFingerOn);
        //指纹开关
        ClickUtil.click(checkedTextView, () -> {
            isFingerOn = SPUtil.get(SPConfig.IS_FINGER_ON, false);
            if (!isFingerOn) {
                FingerprintIdentify mFingerprintIdentify = new FingerprintIdentify(this);
                if (!mFingerprintIdentify.isHardwareEnable()) {
                    ToastUtil.showShort(App.INSTANCE.getString(R.string.mine_securityActivity9_j));
                    return;
                }
                if (!mFingerprintIdentify.isRegisteredFingerprint()) {
                    ToastUtil.showShort(App.INSTANCE.getString(R.string.mine_securityActivity10_j));
                    return;
                }
            }
            checkedTextView.setChecked(!isFingerOn);
            SPUtil.put(SPConfig.IS_FINGER_ON, !isFingerOn);
        });
        mSecurityRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mSecurityRecyclerView.addItemDecoration(new DividerLineItemDecoration(this)
                .setFirstDraw(false)
                .setLastDraw(false)
                .setDividerColor(color(R.color.mine_divider)));

        adapter = SlimAdapter.create().register(R.layout.mine_pay_item, new SlimInjector<PayWayItem>() {
            @Override
            public void onInject(PayWayItem inviteList, IViewInjector iViewInjector, List<Object> list) {
                iViewInjector.text(R.id.item_type_name, inviteList.getTip())
                        .clicked(R.id.item_edit, v -> showDialog(inviteList))
                        .checked(R.id.item_switch, inviteList.getStatus() == 0 ? false : true)
                        .clicked(R.id.item_switch, v -> {
                            mPresenter.requsetCheckSwitch(inviteList);
                        })
                        .image(R.id.imageView, (inviteList.getType().equals("wx") ? R.mipmap.lib_icon_wx : inviteList.getType().equals("bankcard") ? R.mipmap.lib_icon_bank : R.mipmap.lib_icon_alipay))
                        .text(R.id.item_content, inviteList.getNumber() + "  " + inviteList.getName() + "  " + inviteList.getTip());
            }
        }).attachTo(mSecurityRecyclerView);

        itemText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mUserInfo != null) {
                    if (!TextUtils.isEmpty(String.valueOf(mUserInfo.getTpwd()))) {
                        showDialog(null);
                    } else {
                        ToastUtil.showShort(App.INSTANCE.getString(R.string.mine_securityActivity11_j));
                    }
                }

//                }
            }
        });

    }

    public static void start(Context context) {
        Intent intent = new Intent(context, SecurityActivity.class);
        context.startActivity(intent);
    }


    //
    public void updateStatus(UserData user) {
//        ImageUtil.setCircleImage(user.getUpic(), securityImg);
        mUserInfo = user;
        if (user == null) {
            return;
        }
        if (!TextUtils.isEmpty(user.getMobile())) {  // 手机号
            menuBindMobile.setRightString(HideUtil.getPhoneHide(user.getMobile()));
        } else {
            menuBindMobile.setRightString(App.INSTANCE.getString(R.string.mine_securityActivity12_j));
        }
        if (!TextUtils.isEmpty(user.getEmail())) { // 邮箱
            menuBindEmail.setRightString(user.getEmail());
        } else {
            menuBindEmail.setRightString(App.INSTANCE.getString(R.string.mine_securityActivity12_j));
        }
        if (!TextUtils.isEmpty(user.getTpwd())) {  // 资金密码
            menuPayPassword.setRightString(App.INSTANCE.getString(R.string.mine_securityActivity13_j));
        } else {
            menuPayPassword.setRightString(App.INSTANCE.getString(R.string.mine_securityActivity14_j));
        }
        if (user.getStatus() == 1) {  //1 未认证 2 待审核 3 已通过  4拒绝
            menuVerify.setRightString(App.INSTANCE.getString(R.string.mine_securityActivity15_j));
        } else if (user.getStatus() == 2) {
            menuVerify.setRightString(App.INSTANCE.getString(R.string.mine_securityActivity16_j));
        } else if (user.getStatus() == 3) {  // 初级已认证
            if (user.getAuth_status() == 1) {
                menuVerify.setRightString(App.INSTANCE.getString(R.string.mine_securityActivity17_j));
            } else if (user.getAuth_status() == 2) {
                menuVerify.setRightString(App.INSTANCE.getString(R.string.mine_securityActivity18_j));
            } else if (user.getAuth_status() == 3) {
                menuVerify.setRightString(App.INSTANCE.getString(R.string.mine_securityActivity19_j));
            } else {
                menuVerify.setRightString(App.INSTANCE.getString(R.string.mine_securityActivity20_j));
            }
        } else {
            menuVerify.setRightString(App.INSTANCE.getString(R.string.mine_securityActivity21_j));
        }

        if (user.getIs_shop().equals("1")) {  // 商家认证
            menuSeller.setRightString(App.INSTANCE.getString(R.string.mine_securityActivity22_j));
        } else if (user.getIs_shop().equals("0")) {
            menuSeller.setRightString(App.INSTANCE.getString(R.string.mine_verifyHomeActivity6_j));
        } else if (user.getIs_shop().equals("2")) {
            menuSeller.setRightString(App.INSTANCE.getString(R.string.mine_securityActivity24_j));
        } else {
            menuSeller.setRightString(App.INSTANCE.getString(R.string.mine_assetFragment3_j));
        }
        if (0 != user.getIs_start_google()) {  // 谷歌认证
            menuChrome.setRightString(App.INSTANCE.getString(R.string.mine_verifyHomeActivity8_j));
        } else {
            menuChrome.setRightString(App.INSTANCE.getString(R.string.mine_verifyHomeActivity6_j));
        }
        userViewModel.update();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mPresenter.requestUserInfo();
        mPresenter.requsetPayWayList();
    }

    public void cancelShopSuccess() {
        if (userViewModel != null) {
            userViewModel.update();
        }
    }

    public void updateUi(HttpData<List<PayWayItem>> body) {
        if (body.getData().size() < 3) {
            itemText.setVisibility(View.VISIBLE);
        } else {
            itemText.setVisibility(View.GONE);
        }
        adapter.updateData(body.getData());
    }

    /**
     * 显示手机验证码Dialog
     */
    private void showGoogleDialog() {
        googleDialog = new BottomSheetDialog(this);
        View dialogView = LayoutInflater.from(this).inflate(R.layout.bottom_sheet_check_sms, null);
        googleDialog.setContentView(dialogView);
        googleDialog.show();
        TextView btDeal = dialogView.findViewById(R.id.tv_cancel);
        TextView title = dialogView.findViewById(R.id.tv_goto_register);
        mTvCount = dialogView.findViewById(R.id.tv_count);
        EditText etCode = dialogView.findViewById(R.id.et_code);
        EditText etGoogleCode = dialogView.findViewById(R.id.et_google_code);
        Button btSubmit = dialogView.findViewById(R.id.bt_submit);
        String mobile = mUserInfo.getMobile();
        if (mUserInfo.getIs_start_google() == 1) {
            title.setText(App.INSTANCE.getString(R.string.mine_securityActivity27_j));
            googleType = 0;
        } else {
            title.setText(App.INSTANCE.getString(R.string.mine_securityActivity28_j));
            googleType = 1;
        }

        ClickUtil.click(btSubmit, () -> {
            String authCode = etCode.getText().toString();
            if (TextUtils.isEmpty(authCode)) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.mine_securityActivity29_j));
                return;
            }
            if (TextUtils.isEmpty(etGoogleCode.getText())) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.mine_securityActivity30_j));
                return;
            }
            mPresenter.toggleGoogleVerify(googleType, etGoogleCode.getText().toString(), authCode, mobile);
        });

        ClickUtil.click(mTvCount, () -> {
            if (CheckUtil.isEmail(mobile)) {
                mPresenter.sendEmail(mUserInfo.getEmail());
            } else {
                mPresenter.requestAuthCode(mobile);
            }
        });

        ClickUtil.click(btDeal, () -> {
            googleDialog.dismiss();
        });

    }

    public void setGoogleVerifySuccess() {
        if (googleDialog != null) {
            googleDialog.dismiss();
        }
        userViewModel.update();
    }

    public void onAuthCodeSuccess() {
        startCount();
    }

    public void startCount() {
        mTvCount.setEnabled(false);
        disposableSubscriber = new DisposableSubscriber<Long>() {
            @Override
            public void onNext(Long aLong) {
                int time = (int) (60 - aLong);
                if (mTvCount != null) {
                    mTvCount.setText(time + App.INSTANCE.getString(R.string.mine_verifyGoogleActivity2_j));
                    mTvCount.setTextColor(getResources().getColor(R.color.mine_878));
                }
            }

            @Override
            public void onError(Throwable t) {
                System.out.println(t.toString());
            }

            @Override
            public void onComplete() {
                if (mTvCount != null) {
                    mTvCount.setText(App.INSTANCE.getString(R.string.mine_verifyGoogleActivity3_j));
                    mTvCount.setEnabled(true);
                }
                if (!disposableSubscriber.isDisposed()) {
                    disposableSubscriber.dispose();
                    disposableSubscriber = null;
                }

            }
        };
        Flowable.interval(0, 1, TimeUnit.SECONDS, Schedulers.newThread())
                .take(60)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(disposableSubscriber);
    }

    /**
     * 添加支付方式
     *
     * @param item
     */
    public void showDialog(PayWayItem item) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.MineDialogStyleBottom);
        View inflate = LayoutInflater.from(this).inflate(R.layout.mine_dialog_edit_pay_way, null);
        builder.setView(inflate);

        et_bankname = inflate.findViewById(R.id.et_bankname);
        tv_name = inflate.findViewById(R.id.dialog_name);
        et_bank_code = inflate.findViewById(R.id.dialog_bank_code);
        et_bank_othername = inflate.findViewById(R.id.dialog_bank_othername);
        et_pwd = inflate.findViewById(R.id.dialog_pwd);
        tv_cancle = inflate.findViewById(R.id.tv_cancle);
        tv_confirm = inflate.findViewById(R.id.tv_confirm);
        tv_close = inflate.findViewById(R.id.tv_close);

        tv_name.setText(mUserInfo.getName());

        ClickUtil.click(tv_cancle, () -> {
            if (mAlertDialog != null) {
                mAlertDialog.dismiss();
            }
        });
        ClickUtil.click(tv_close, () -> {
            if (mAlertDialog != null) {
                mAlertDialog.dismiss();
            }
        });
        ClickUtil.click(tv_confirm, () -> {
            String bank = et_bankname.getText().toString().trim();//开户银行
            String name = tv_name.getText().toString().trim();//开户名
            String bank_code = et_bank_code.getText().toString().trim();//银行卡账号
            String bank_name = et_bank_othername.getText().toString().trim();//开户支行
            String pwd = et_pwd.getText().toString().trim();//资金密码

            if (TextUtils.isEmpty(bank)) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.mine_securityActivity33_j));
                return;
            }
            if (TextUtils.isEmpty(name)) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.mine_securityActivity34_j));
                return;
            }
            if (TextUtils.isEmpty(bank_code)) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.mine_securityActivity35_j));
                return;
            }
            if (TextUtils.isEmpty(bank_name)) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.mine_securityActivity36_j));
                return;
            }
            if (TextUtils.isEmpty(pwd)) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.mine_shellActivity5_j));
                return;
            }
            mPresenter.requestAddPayWay2("add", "bankcard", bank, name, bank_code, bank_name, pwd);
        });

//        if (item != null) {
//            et_bankname.setText(item.getBank());
//            tv_name.setText(item.getName());
//            et_bank_code.setText(item.getNumber());
//            et_bank_othername.setText(item.);
//            et_pwd.setText(item.);
//        }

//        mDialogBanknumLayout = inflate.findViewById(R.id.dialog_banknum_layout);
//        dialogPaypalLayout = inflate.findViewById(R.id.dialog_paypal_layout);
//        mDialogInputBankName = inflate.findViewById(R.id.dialog_input_bank_name);
//        mDialogInputBankCardNum = inflate.findViewById(R.id.dialog_input_bankcard_num);
//        mDialogInputBankBranch = inflate.findViewById(R.id.dialog_input_bank_branch_name);
//        mDialogThirdpartyLayout = inflate.findViewById(R.id.dialog_thirdparty_layout);
//        mDialogThirdpartyName = inflate.findViewById(R.id.thirdparty_name);
//        mDialogInputThirdpartyAccount = inflate.findViewById(R.id.dialog_input_thirdparty_account);
//        dialogInputPaypalName = inflate.findViewById(R.id.dialog_input_paypal_name);
//        mDialogThirdpartyPic = inflate.findViewById(R.id.dialog_thirdparty_pic);
//        mDialogThirdpartyPicHint = inflate.findViewById(R.id.dialog_thirdparty_pic_hint);
//        mDialogPayWaySpinner = inflate.findViewById(R.id.dialog_pay_way_spinner);
//        if (item == null) {  // 添加支付方式
//            mDialogPayWaySpinner.setEnabled(true);
//        } else {  // 修改支付方式
//            mDialogPayWaySpinner.setEnabled(false);
//        }
//        mDialogRealname = inflate.findViewById(R.id.dialog_realname);
//        mDialogInputPayPwd = inflate.findViewById(R.id.dialog_input_pay_pwd);
//        CheckBox checkBox = inflate.findViewById(R.id.checkBox);
//        checkBox.setOnCheckedChangeListener((buttonView, isChecked) -> {
//            if (isChecked) {
//                mDialogInputPayPwd.setTransformationMethod(new HideReturnsTransformationMethod());
//            } else {
//                mDialogInputPayPwd.setTransformationMethod(new PasswordTransformationMethod());
//            }
//        });
//        mDialogClose = inflate.findViewById(R.id.dialog_close);
//        mDialogCancel = inflate.findViewById(R.id.dialog_cancel);
//        mDialogSubmit = inflate.findViewById(R.id.dialog_submit);  // 完成设置
//
//        List<String> data = new ArrayList<>();
//        data.add(App.INSTANCE.getString(R.string.mine_shellActivity7_j));
//        data.add(App.INSTANCE.getString(R.string.mine_securityActivity39_j));
//        data.add(App.INSTANCE.getString(R.string.mine_securityActivity40_j));
//        mDialogPayWaySpinner.attachData(data);
//
//        mDialogPayWaySpinner.setOnSelectListener(position -> {
//            mSelectName = data.get(position);
//            checkLayout();
//        });
//        if (item != null) {
//            if ("bankcard".equals(item.getType())) {
//                mDialogPayWaySpinner.setSelectIndex(0);
//                mDialogInputBankName.setText(item.getBank());
//                mDialogInputBankBranch.setText(item.getBranch());
//                mDialogInputBankCardNum.setText(item.getNumber());
//            } else if ("wx".equals(item.getType())) {
//                mDialogPayWaySpinner.setSelectIndex(1);
//                mDialogInputThirdpartyAccount.setText(item.getNumber());
//            } else if ("alipay".equals(item.getType())) {
//                mDialogPayWaySpinner.setSelectIndex(2);
//                mDialogInputThirdpartyAccount.setText(item.getNumber());
//            } else if ("paypal".equals(item.getType())) {
//                mDialogPayWaySpinner.setSelectIndex(3);
//                dialogInputPaypalName.setText(item.getNumber());
//            }
//            mDialogRealname.setText(item.getName());
//            mType = "edit";
//        } else {
//            mType = "add";
//            mDialogPayWaySpinner.setSelectIndex(0);
//            if (mUserInfo != null) {
//                setText(mDialogRealname, mUserInfo.getName());
//            }
//        }
//
//        ClickUtil.click(mDialogClose, () -> {
//            if (mAlertDialog != null) {
//                mAlertDialog.dismiss();
//            }
//        });
//        ClickUtil.click(mDialogCancel, () -> {
//            if (mAlertDialog != null) {
//                mAlertDialog.dismiss();
//            }
//        });
//        ClickUtil.click(mDialogThirdpartyPic, () -> {
//            PictureSelector.create(this)
//                    .openGallery(PictureMimeType.ofImage())
//                    .selectionMode(PictureConfig.SINGLE)
//                    .forResult(PictureConfig.CHOOSE_REQUEST);
//        });
//        ClickUtil.click(mDialogSubmit, () -> {
//            String bankName = mDialogInputBankName.getText().toString().trim();  // 银行开户行
//            String bankBranch = mDialogInputBankBranch.getText().toString().trim();  // 开户银行支行
//            String bankNum = mDialogInputBankCardNum.getText().toString().trim();  // 银行卡号
//            String account = mDialogInputThirdpartyAccount.getText().toString().trim();  // 支付宝账号
//            String payPwd = mDialogInputPayPwd.getText().toString().trim();  // 资金密码
//            String paypalAccount = dialogInputPaypalName.getText().toString().trim();  // Paypal账户
//            String payName = "";
//            if (App.INSTANCE.getString(R.string.mine_shellActivity7_j).equals(mSelectName)) {
//                if (TextUtils.isEmpty(bankName)) {
//                    ToastUtil.showShort(App.INSTANCE.getString(R.string.mine_securityActivity33_j));
//                    return;
//                }
//                if (TextUtils.isEmpty(bankBranch)) {
//                    ToastUtil.showShort(App.INSTANCE.getString(R.string.mine_securityActivity36_j));
//                    return;
//                }
//                if (TextUtils.isEmpty(bankNum)) {
//                    ToastUtil.showShort(App.INSTANCE.getString(R.string.mine_securityActivity41_j));
//                    return;
//                }
//                if (bankNum.length() < 10 || bankNum.length() > 20) {
//                    ToastUtil.showShort(App.INSTANCE.getString(R.string.mine_securityActivity42_j));
//                    return;
//                }
//                payName = "bankcard";
//            } else if (App.INSTANCE.getString(R.string.mine_securityActivity39_j).equals(mSelectName)) {
//                if (TextUtils.isEmpty(account)) {
//                    ToastUtil.showShort(App.INSTANCE.getString(R.string.mine_securityActivity43_j));
//                    return;
//                }
//                if (TextUtils.isEmpty(imgUrl)) {
//                    ToastUtil.showShort(App.INSTANCE.getString(R.string.mine_securityActivity44_j));
//                    return;
//                }
//                payName = "wx";
//            } else if (App.INSTANCE.getString(R.string.mine_securityActivity40_j).equals(mSelectName)) {
//                if (TextUtils.isEmpty(account)) {
//                    ToastUtil.showShort(App.INSTANCE.getString(R.string.mine_securityActivity45_j));
//                    return;
//                }
//                if (TextUtils.isEmpty(imgUrl)) {
//                    ToastUtil.showShort(App.INSTANCE.getString(R.string.mine_securityActivity46_j));
//                    return;
//                }
//                payName = "alipay";
//            } else if ("Paypal".equals(mSelectName)) {  // payPal支付
//                if (TextUtils.isEmpty(paypalAccount)) {
//                    ToastUtil.showShort(App.INSTANCE.getString(R.string.mine_securityActivity45_j));
//                    return;
//                }
//                payName = "paypal";
//            }
//            if (TextUtils.isEmpty(payName)) {
//                ToastUtil.showShort(App.INSTANCE.getString(R.string.mine_securityActivity47_j));
//                return;
//            }
//            if (TextUtils.isEmpty(payPwd)) {
//                ToastUtil.showShort(App.INSTANCE.getString(R.string.mine_securityActivity48_j));
//                return;
//            }
//            // 添加/编辑   支付方式   银行 银行 银行  支付宝账号/微信账号  支付宝图片/微信图片    资金密码
//            mPresenter.requestAddPayWay(mType, payName, bankName, bankBranch, bankNum, "Paypal".equals(mSelectName) ? paypalAccount : account, imgUrl, payPwd);
//
//        });
        mAlertDialog = builder.create();
        mAlertDialog.show();
        int width = (int) (ScreenUtils.getScreenSize(this)[0] * 0.9);
        mAlertDialog.getWindow().setLayout(width, LinearLayout.LayoutParams.WRAP_CONTENT);
    }

    /**
     * 当添加或修改支付方式成功
     */
    public void onChangePayWaySuccess() {
        userViewModel.update();
        mImagePath = "";
        imgUrl = "";
        if (mAlertDialog != null) {
            mAlertDialog.dismiss();
        }
    }

    private void checkLayout() {
        if (App.INSTANCE.getString(R.string.mine_shellActivity7_j).equals(mSelectName)) {
            mDialogBanknumLayout.setVisibility(View.VISIBLE);  // 银行卡相关信息
            mDialogThirdpartyLayout.setVisibility(View.GONE);  // 支付宝 微信相关信息
            dialogPaypalLayout.setVisibility(View.GONE);  // PAYpal账户
        } else if (App.INSTANCE.getString(R.string.mine_securityActivity39_j).equals(mSelectName)) {
            mDialogBanknumLayout.setVisibility(View.GONE);
            mDialogThirdpartyLayout.setVisibility(View.VISIBLE);
            dialogPaypalLayout.setVisibility(View.GONE);
            mDialogThirdpartyName.setText(App.INSTANCE.getString(R.string.mine_securityActivity49_j));
            mDialogInputThirdpartyAccount.setHint(String.format(App.INSTANCE.getString(R.string.mine_securityActivity50_j), App.INSTANCE.getString(R.string.mine_securityActivity39_j)));
            mDialogThirdpartyPicHint.setText(App.INSTANCE.getString(R.string.mine_securityActivity51_j));
        } else if (App.INSTANCE.getString(R.string.mine_securityActivity40_j).equals(mSelectName)) {
            dialogPaypalLayout.setVisibility(View.GONE);
            mDialogBanknumLayout.setVisibility(View.GONE);
            mDialogThirdpartyLayout.setVisibility(View.VISIBLE);
            mDialogThirdpartyName.setText(App.INSTANCE.getString(R.string.mine_securityActivity52_j));
            mDialogInputThirdpartyAccount.setHint(String.format(App.INSTANCE.getString(R.string.mine_securityActivity50_j), App.INSTANCE.getString(R.string.mine_securityActivity40_j)));
            mDialogThirdpartyPicHint.setText(App.INSTANCE.getString(R.string.mine_securityActivity53_j));
        } else if ("Paypal".equals(mSelectName)) {
            dialogPaypalLayout.setVisibility(View.VISIBLE);
            mDialogBanknumLayout.setVisibility(View.GONE);
            mDialogThirdpartyLayout.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片、视频、音频选择结果回调
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    LocalMedia media = selectList.get(0);
                    if (media.isCompressed()) {
                        mImagePath = media.getCompressPath();
                    } else {
                        mImagePath = media.getPath();
                    }
                    ImageUtil.setImage(mImagePath, mDialogThirdpartyPic);
                    mPresenter.submitVerify(new File(mImagePath));

                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true  注意：音视频除外
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true  注意：音视频除外
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    //                    adapter.setList(selectList);
                    //                    adapter.notifyDataSetChanged();
                    break;
            }

        }
    }

    /**
     * 当支付方式开关切换成功
     *
     * @param item
     */
    public void onChangeSwitchSuccess(PayWayItem item) {
        userViewModel.update();
        adapter.notifyDataSetChanged();
    }

    public void dismissShow() {
        userViewModel.update();
        materialDialog.dismiss();
        mPresenter.requestUserInfo();
    }

    public void uploadFail() {
        Glide.with(this).load(getResources().getDrawable(R.mipmap.mine_add_pay)).into(mDialogThirdpartyPic);
    }

    public void putList(String url) {
        imgUrl = url;
    }

}
